<template>
  <div class="card w-full max-w-md bg-base-100/80 shadow-2xl">
    <div class="card-body">
      <!-- 标题区域 -->
      <div class="text-center mb-6">
        <div class="avatar avatar-placeholder mx-auto">
          <div class="w-20 rounded-full bg-primary text-primary-content flex items-center justify-center">
            <i class="fa fa-sign-in" style="font-size: 2rem;"></i>
          </div>
        </div>
        <h2 class="text-3xl font-bold text-primary">验证码登录</h2>
        <p class="text-base-content/70 mt-2">使用手机或邮箱验证码登录</p>
      </div>

      <!-- 切换登录方式 -->
      <div class="tabs tabs-boxed mb-6">
        <a
            class="tab"
            :class="{ 'tab-active': loginType === 'phone' }"
            @click="loginType = 'phone'"
        >
          <i class="fa fa-mobile mr-2"></i>手机验证码
        </a>
        <a
            class="tab"
            :class="{ 'tab-active': loginType === 'email' }"
            @click="loginType = 'email'"
        >
          <i class="fa fa-envelope mr-2"></i>邮箱验证码
        </a>
      </div>

      <!-- 手机号/邮箱输入 -->
      <div class="form-control">
        <label class="label">
          <span class="label-text">
            <i class="fa mr-2" :class="loginType === 'phone' ? 'fa-mobile' : 'fa-envelope'"></i>
            {{ loginType === 'phone' ? '手机号' : '邮箱' }}
          </span>
        </label>
        <input
            type="text"
            :placeholder="loginType === 'phone' ? '请输入手机号' : '请输入邮箱'"
            class="input input-bordered w-full"
            v-model="contactInfo"
        />
      </div>

      <!-- 图片验证码 -->
      <div class="form-control mt-4">
        <label class="label">
          <span class="label-text">
            <i class="fa fa-shield mr-2"></i>
            图片验证码
          </span>
        </label>
        <div class="flex gap-2">
          <input
              type="text"
              placeholder="请输入图片验证码"
              class="input input-bordered flex-1"
              v-model="captchaCode"
          />
          <div
              class="bg-base-300 p-2 rounded-box flex items-center justify-center min-w-24 cursor-pointer hover:bg-base-200 transition-colors"
              @click="refreshCaptcha"
              :class="{ 'cursor-not-allowed': captchaLoading }"
          >
            <div v-if="captchaLoading" class="loading loading-spinner loading-sm"></div>
            <img v-else :src="captchaImage" alt="验证码" class="h-10 rounded" />
          </div>
        </div>
        <p class="text-xs text-base-content/60 mt-1" @click="refreshCaptcha" style="cursor: pointer;">
          看不清？点击图片刷新
        </p>
      </div>

      <!-- 发送验证码按钮 -->
      <div class="form-control mt-4">
        <button
            class="btn btn-primary w-full"
            :disabled="!canSendCode || sendCodeLoading"
            @click="sendVerificationCode"
        >
          <span v-if="sendCodeLoading" class="loading loading-spinner loading-sm mr-2"></span>
          {{ countdown > 0 ? `重新发送(${countdown}s)` : '发送验证码' }}
        </button>
      </div>

      <!-- 验证码输入 -->
      <div class="form-control mt-6" v-if="codeSent">
        <label class="label">
          <span class="label-text">
            <i class="fa fa-key mr-2"></i>
            验证码
          </span>
        </label>
        <div class="flex gap-2 justify-center">
          <input
              v-for="(_, index) in 6"
              :key="index"
              type="text"
              maxlength="1"
              class="input input-bordered w-12 h-12 text-center text-lg focus:ring-2 focus:ring-primary"
              v-model="verificationCodeDigits[index]"
              @input="handleCodeInput(index, $event)"
              @keydown="handleKeyDown(index, $event)"
              ref="codeInputs"
              :class="{ 'input-error': showCodeError }"
          />
        </div>
        <p v-if="showCodeError" class="text-error text-xs mt-1">验证码错误，请重新输入</p>
      </div>

      <!-- 登录按钮 -->
      <div class="form-control mt-6" v-if="codeSent">
        <button
            class="btn btn-primary w-full"
            :disabled="!canLogin || loginLoading"
            @click="login"
        >
          <span v-if="loginLoading" class="loading loading-spinner loading-sm mr-2"></span>
          <i class="fa fa-check-circle mr-2"></i>
          登录
        </button>
      </div>

      <!-- 分隔线 -->
      <div class="divider my-6">或</div>

      <!-- 第三方登录 -->
      <div class="grid grid-cols-3 gap-4">
        <button class="btn btn-outline flex flex-col items-center justify-center py-3">
          <i class="fa fa-weixin text-green-500 text-xl mb-1"></i>
          <span class="text-xs">微信</span>
        </button>
        <button class="btn btn-outline flex flex-col items-center justify-center py-3">
          <i class="fa fa-qq text-blue-500 text-xl mb-1"></i>
          <span class="text-xs">QQ</span>
        </button>
        <button class="btn btn-outline flex flex-col items-center justify-center py-3">
          <i class="fa fa-github text-gray-700 text-xl mb-1"></i>
          <span class="text-xs">GitHub</span>
        </button>
      </div>

      <!-- 注册链接 -->
      <div class="text-center mt-6">
        <p class="text-sm text-base-content/70">
          还没有账号?
          <router-link class="link link-primary font-medium" to="/guest/register">立即注册</router-link>
        </p>
      </div>
    </div>
  </div>
  
  <!-- 提示框 -->
  <transition name="fade">
    <div v-if="toast.show" class="toast toast-top toast-center z-50" :class="toast.type">
      <i class="fa mr-2" :class="{
          'fa-check-circle': toast.type === 'alert-success',
          'fa-exclamation-circle': toast.type === 'alert-error',
          'fa-info-circle': toast.type === 'alert-info'
        }"></i>
      {{ toast.message }}
    </div>
  </transition>
</template>

<script>
export default {
  name: 'LoginCode',
  data() {
    return {
      // 登录类型：手机号或邮箱
      loginType: 'phone',
      contactInfo: '',
      captchaCode: '',
      captchaImage: '',
      captchaLoading: false,
      sendCodeLoading: false,
      loginLoading: false,
      codeSent: false,
      countdown: 0,
      verificationCodeDigits: ['', '', '', '', '', ''],
      showCodeError: false,
      toast: {
        show: false,
        message: '',
        type: 'alert-info'
      }
    }
  },
  computed: {
    // 是否可以发送验证码
    canSendCode() {
      if (this.countdown > 0) return false;
      if (this.loginType === 'phone') {
        return this.isValidPhone(this.contactInfo) && this.captchaCode.length >= 4;
      } else {
        return this.isValidEmail(this.contactInfo) && this.captchaCode.length >= 4;
      }
    },
    
    // 是否可以登录
    canLogin() {
      return this.codeSent && this.verificationCodeDigits.every(digit => digit !== '');
    }
  },
  mounted() {
    this.refreshCaptcha();
  },
  watch: {
    // 监听登录类型变化，重置相关状态
    loginType() {
      this.contactInfo = '';
      this.captchaCode = '';
      this.codeSent = false;
      this.verificationCodeDigits = ['', '', '', '', '', ''];
      this.showCodeError = false;
      this.refreshCaptcha();
    }
  },
  methods: {
    // 模拟图片验证码
    refreshCaptcha() {
      this.captchaLoading = true;
      // 模拟加载延迟
      setTimeout(() => {
        // 生成随机验证码图片（实际项目中应从后端获取）
        this.captchaImage = `https://picsum.photos/100/40?random=${Date.now()}`;
        this.captchaLoading = false;
      }, 500);
    },
    
    // 验证手机号
    isValidPhone(phone) {
      return /^1[3-9]\d{9}$/.test(phone);
    },
    
    // 验证邮箱
    isValidEmail(email) {
      return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    },
    
    // 发送验证码
    sendVerificationCode() {
      if (!this.canSendCode) return;

      this.sendCodeLoading = true;
      this.showCodeError = false;

      // 模拟发送验证码
      setTimeout(() => {
        this.sendCodeLoading = false;
        this.codeSent = true;
        this.countdown = 60;

        // 开始倒计时
        const timer = setInterval(() => {
          this.countdown--;
          if (this.countdown <= 0) {
            clearInterval(timer);
            // 重置图片验证码，要求用户重新输入
            this.captchaCode = '';
            this.refreshCaptcha();
          }
        }, 1000);

        // 显示成功提示
        this.showToast('验证码已发送，请注意查收', 'alert-success');

        // 聚焦到第一个验证码输入框
        this.$nextTick(() => {
          if (this.$refs.codeInputs && this.$refs.codeInputs[0]) {
            this.$refs.codeInputs[0].focus();
          }
        });
      }, 1000);
    },
    
    // 处理验证码输入
    handleCodeInput(index, event) {
      const value = event.target.value;

      // 确保只输入数字
      if (!/^\d*$/.test(value)) {
        this.$set(this.verificationCodeDigits, index, '');
        return;
      }

      // 自动跳到下一个输入框
      if (value && index < 5) {
        this.$nextTick(() => {
          if (this.$refs.codeInputs && this.$refs.codeInputs[index + 1]) {
            this.$refs.codeInputs[index + 1].focus();
          }
        });
      }
    },
    
    // 处理键盘事件
    handleKeyDown(index, event) {
      // 处理删除键
      if (event.key === 'Backspace' && !this.verificationCodeDigits[index] && index > 0) {
        this.$nextTick(() => {
          if (this.$refs.codeInputs && this.$refs.codeInputs[index - 1]) {
            this.$refs.codeInputs[index - 1].focus();
          }
        });
      }
    },
    
    // 登录
    login() {
      if (!this.canLogin) return;

      this.loginLoading = true;

      // 模拟登录请求
      setTimeout(() => {
        this.loginLoading = false;

        // 模拟登录成功
        this.showToast('登录成功', 'alert-success');

        // 实际项目中应该跳转到首页或其他页面
        // this.$router.push('/');
      }, 1500);
    },
    
    // 显示提示
    showToast(message, type = 'alert-info') {
      this.toast = {
        show: true,
        message,
        type
      };

      // 3秒后自动关闭
      setTimeout(() => {
        this.toast.show = false;
      }, 3000);
    }
  }
}
</script>

<style scoped>
/* 可以添加自定义样式 */
.card {
  overflow: visible;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>